package org.com.Service.Impl;

import Entity.Shop;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.com.Mapper.ShopMapper;
import org.com.Service.IShopService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 277
 * @since 2025-10-20
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Value("${imgurl.path}")
    String path;
    @Value("${server.port}")
    String port;


    @Override
    public String upload(MultipartFile file, HttpServletRequest request) {
        String originalFilename = file.getOriginalFilename();
        String fileextension = UUID.randomUUID().toString();
        String filename = fileextension + originalFilename.substring(originalFilename.lastIndexOf("."));
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            //保存文件
            Path fileppath = Paths.get(path, filename);
            Files.copy(file.getInputStream(), fileppath);
//构造可访问的url
            String imgurl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/shop/imgs/" + filename;
            return imgurl;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public byte[] getimg(String filename) throws IOException {

        try {
            Path imagePath = Paths.get(path, filename);
            if (Files.exists(imagePath)) {
                return Files.readAllBytes(imagePath);
            } else {
                throw new IOException("图片不存在: " + filename);
            }
        } catch (IOException e) {
            // 返回默认图片或错误图片
            throw e;
        }
    }


}
